package com.weakteam.orderonline.dataresource.domain;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.*;
import java.io.Serializable;

/**
 * @author Nail
 */

@Entity
@javax.persistence.Table(name = "\"PLACES\"")
public class Place implements Serializable {

    private static final Logger log = LoggerFactory.getLogger(Place.class);

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "\"PLACES_id_seq\"")
    @SequenceGenerator(name = "\"PLACES_id_seq\"", sequenceName = "\"PLACES_id_seq\"")

    @Column(name = "\"id\"")
    private Integer id;

    @Column(name = "\"name\"", nullable = false)
    private String name;

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public JSONObject getJSONObject() {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("id", id);
        jsonObj.put("name", name);
        return jsonObj;
    }

    public String getJSON() {
        StringBuilder json = new StringBuilder();
        json.append("{\"id\":").append(id).append(",");
        json.append("\"name\":\"").append(name).append("\"}");
        return json.toString();
    }

    public void setJSON(String json) {
        if (json!=null && json.length() > 0){
            try {
                JSONParser parser = new JSONParser();
                JSONObject jObj = (JSONObject)parser.parse(json);
                this.setJSON(jObj);
            } catch (ParseException e) {
                log.error("try to parse json" + e);
            }
        }
    }

    public void setJSON(JSONObject jObj) {
        Object obj = null;

        obj = jObj.get("id");
        if (obj != null) {
            this.id = ((Long)obj).intValue();
        }

        obj = jObj.get("name");
        if (obj != null) {
            this.name = (String)obj;
        }
    }

}
